import ajax from '@api/ajax'
import * as api from '@api/url'
export default {
  namespaced: true,
  state: {
    menus: [],
    activedMenuIndex: 0 // 激活菜单下标序号
  },
  getters: {
    menus: s => s.menus,
    activedMenuIndex: s => s.activedMenuIndex,
    activedMenu: s => s.menus[s.activedMenuIndex] || []
  },
  mutations: {
    updateMenus (s, v) {
      s.menus = v
    },
    updateActivedMenuIndex (s, v) {
      sessionStorage.setItem('activedMenuIndex', v)
      s.activedMenuIndex = v
    }
  },
  actions: {
    /**
     * 获取用户菜单
     * @param {*} context
     */
    queryMenus ({commit}) {
      commit('updateActivedMenuIndex', sessionStorage.getItem('activedMenuIndex') || 0)
      let menus = sessionStorage.getItem('menus')
      if (menus) {
        commit('updateMenus', JSON.parse(menus))
      } else {
        const name = sessionStorage.getItem('userName')
        ajax.post(api.GET_USER_MENU, {type: '3', name}).then(({data}) => {
          sessionStorage.setItem('menus', JSON.stringify(data))
          commit('updateMenus', data)
        })
      }
    },
    /**
     * 退出登录
     * @param {*} context
     */
    logout ({commit}) {
      return new Promise((resolve, reject) => {
        ajax.post(api.LOGOUT, {}).then(res => {
          sessionStorage.removeItem('menus')
          sessionStorage.removeItem('activedMenuIndex')
          commit('updateMenus', '')
          commit('updateActivedMenuIndex', 0)
          resolve(res)
        }).catch(reject)
      })
    }
  }
}
